<?php

class Application_Model_OrderItem extends Application_Model_DomainObject {

    protected $_id;
    protected $_orderId;
    protected $_price;
    protected $_productId;
    protected $_quantity;
    protected $_productName;
    protected $_comment;
    protected $_skuNo;
    protected $_status;
    protected $_description;
    protected $_taoBaoUrl;
    protected $_problemContent; //问题原因
    protected $_ckPass;
    /**
     * 已退款
     */
    const Status_Refund = 1;
    /**
     * 少货
     */
    const Status_Less = 2;
    /**
     * 发错货
     */
    const Status_Error = 3;
    

    /**
     * 返回数据持久化对象
     * @return Application_Model_DbTable_OrderItem
     */
    private static function getDb() {
        return new Application_Model_DbTable_OrderItem();
    }

    /**
     * 根据orderId返回一个orderItem数组
     * @param int $orderId
     * @return array
     */
    public static function getByOrderId($orderId) {
        return Application_Model_OrderItem::getDb()->queryAll(array('orderId' => $orderId));
    }
    
    public static function getNumByOrderId($orderId){
        return Application_Model_OrderItem::getDb()->count(array('(status is null or status != '=>1,' ) and orderId = ' => $orderId));
    }

    protected $_product;

    public function getProduct() {
        if ($this->_product == NULL)
            $this->_product = new Application_Model_Product($this->_productId);
        return $this->_product;
    }

    protected $_sku;

    public function getSku() {
        if ($this->_sku == NULL && $this->_skuNo != null && $this->_skuNo != '')
            $this->_sku = Application_Model_Sku::getBySkuNo($this->_skuNo);
        return $this->_sku;
    }

    private $image;

    public function getImage() {
        if ($this->image != NULL)
            return $this->image;

        if ($this->getSku() != NULL)
            $this->image = $this->getSku()->Image;

        if ($this->image == NULL)
            $this->image = $this->getProduct()->Image;

        if ($this->image == NULL)
            $this->image = Application_Model_Product::DEFAULT_IMAGE;

        return $this->image;
    }

    public function getStatusText() {
        $order = Application_Model_Order::load($this->_orderId);
        
        if($order->isAbnormal>0 && $order->rechangeStatus) {
            $names = array(1 => '缺货退款', 2 => '少货', 3 => '发错货', 4 => '取消并退款', NULL => '正常入库', 0 => '正常入库');
            return $names[$this->_status];
        }
        if($order->status == Application_Model_Order::STATUS_INSTORE){
            return $order->IsInStore?"正常入库":"";
        }
        return ;
    }
    
    public function getStatusName() {
        $order = Application_Model_Order::load($this->_orderId);
        if($this->_status == Application_Model_OrderItem::Status_Less) {
            return ($order->scheme == Application_Model_Order::Scheme_ReturnMoney?($order->rechangeStatus == Application_Model_Order::ReChange_Complete?"已退款":"等待退款"):"");
        }
        return ;
    }

    public function getbyproductd() {
        return Application_Model_Product::load($this->_productId);
    }

    /**
     * 获取OrderItem的URL地址
     * 1、先判断是否已经有淘宝推广的URL，如有则直接返回
     * 2、如没有，则通过API调用URL，再更新OrderItem的TaoBaoUrl字段。
     * @param type $product
     * @param type $orderItem
     * @return type
     */
    public static function GetTopUrl($product, $orderItem) {
        //return $product->url;
        if ($orderItem->taoBaoUrl != '') {
            //已经存在taobalUrl,则直接返回
            return $orderItem->taoBaoUrl;
        } else {
            //taoBaoUrl为空，通过API获取推广URL，并保存到orderItem->taoBalUrl.
            //return $product->url;
            $taobalReader = new Uuch_Reader_TaobaoReader();
            $topUrl = $taobalReader->getTopUrl($product->name, $product->url);
            if ($topUrl != NULL) {
                $orderItem->taoBaoUrl = $topUrl;
                $orderItem->save();
                return $orderItem->taoBaoUrl;
            } else {
                return $product->url;
            }
        }
    }

    public function getTaobaoTopUrl() {
        //echo $this->_taoBaoUrl;
        if ($this->_taoBaoUrl != "") {
            return $this->_taoBaoUrl;
        } else {
            $product = Application_Model_Product::load($this->_productId);
            if (strpos($product->url, "taobao") > 0 || strpos($product->url, "tmall") > 0) {
                $taobalReader = new Uuch_Reader_TaobaoReader();
                $topUrl = $taobalReader->getTopUrl($product->name, $product->url);
                if ($topUrl != NULL) {
                    return $topUrl;
                } else {
                    return $product->url;
                }
            } else {
                return $product->url;
            }
        }
    }

    public static function singleRetuenMoney($id, $userid, $num) {
        $obj = Application_Model_OrderItem::load($id);
        if ($obj) {
            if ($obj->status == null) {
                try {
                    $db = Application_Model_OrderItem::getDb();
                    $db->beginTran();

                    $obj->status = 1;   //单个退款，状态为1
                    $obj->save();

                    $accountObj = Application_Model_UserAccount::load($userid);

                    $beforeMoney = $accountObj->money;

                    $accountObj->money = $accountObj->money + ($obj->price * $obj->quantity);
                    $accountObj->save();
                    Application_Model_Operate::addOperate(($obj->price * $obj->quantity), null, $id, "代购运单 " . $obj->getOrderNum() . " 中商品单项退款", $userid);
                    $dateCreated = date('Y-m-d H:i:s', time());
                    $comment = "代购订单:" . $obj->getOrderNum() . '中商品"' . mb_substr($obj->productName, 0, 8, 'utf-8') . '···"单项退款';

                    $afterMoney = $beforeMoney + ($obj->price * $obj->quantity);

                    $userAccountHistory = new Application_Model_UserAccountHistory();
                    $userAccountHistory->type = 4;
                    $userAccountHistory->beforeMoney = $beforeMoney;
                    $userAccountHistory->afterMoney = $afterMoney;
                    $userAccountHistory->comment = $comment;
                    $userAccountHistory->dateCreated = $dateCreated;
                    $userAccountHistory->relaseId = $id;
                    $userAccountHistory->accountId = $userid;
                    $userAccountHistory->State = Application_Model_UserAccountHistory::STATE_MONEY;
                    $userAccountHistory->save();

                    $isAllReturn = true;
                    $order = Application_Model_Order::load($obj->orderId);
                    $itemList = $order->getshipdetail();
                    foreach ($itemList as $item) {
                        if ($item->status == 0) {
                            $isAllReturn = false;
                            break;
                        }
                    }

                    //判断是否全部都退款了，如果是则更新整个订单为 11 全部退款
                    if ($isAllReturn) {
                        //全都退款了，要更新整个订单，状态为11：全部退款
                        $order->status = 10;
                        if ($order->problem == Application_Model_Order::Problem_Appear)
                            $order->problem = Application_Model_Order::Problem_Complete;
                        $order->save();
                        if ($num == 1) { // 1代表退运费
                            //检查是否有运费，如有，则把运费也退回去
                            $shipFee = (int) ($order->shipFee);
                            if ($shipFee > 0) {
                                $beforeMoney = $accountObj->money;

                                $accountObj->money = $accountObj->money + $shipFee;
                                $accountObj->save();
                                Application_Model_Operate::addOperate($shipFee, null, $id, "代购运单 " . $obj->getOrderNum() . " 中运费退款", $userid);
                                $dateCreated = date('Y-m-d H:i:s', time());
                                $comment = "代购订单:" . $obj->getOrderNum() . '商品运费退款';

                                $afterMoney = $beforeMoney + $shipFee;

                                $userAccountHistory = new Application_Model_UserAccountHistory();
                                $userAccountHistory->type = 4;
                                $userAccountHistory->beforeMoney = $beforeMoney;
                                $userAccountHistory->afterMoney = $afterMoney;
                                $userAccountHistory->comment = $comment;
                                $userAccountHistory->dateCreated = $dateCreated;
                                $userAccountHistory->relaseId = $id;
                                $userAccountHistory->accountId = $userid;
                                $userAccountHistory->State = Application_Model_UserAccountHistory::STATE_MONEY;
                                $userAccountHistory->save();
                            }
                        }
                    } else {
                        //状态：12 部分退款
                        //$order->status = 12;
                        $order->save();
                    }

                    $db->commit();
                } catch (Exception $ex) {
                    $db->rollBack();
                    return 0;
                }

                return 1;
            }
        } else {
            return 0;
        }
    }

    public function getOrderNum() {
        $result = Application_Model_Order::load($this->_orderId);
        return 'U2013' . $result->id . substr($result->dateCreated, 17, 1);
    }

    public static function countItem($id) {
        $result = self::load($id);
        if ($result) {
            $where[" orderId = "] = $result->orderId;
            $where[" and status is null and "] = 1; //1代表已经退款
            $countNum = self::getDao()->queryAll($where);
            $num = count($countNum);
        } else {
            $num = 0;
        }
        return $num;
    }

    public static function getOrderIdByProductName($productName, $orderId) {
        $where[' productName like '] = "%" . $productName . "%";
        $where[' or orderId = '] = $orderId;
        return self::getDao()->queryAll($where);
    }

    public static function getSingleAll() {
        return self::getDao()->queryAll(array("status" => 1));
    }
    

}
